package main

import (
	"coding.net/vco/mder/models"
	"coding.net/vco/mder/modules/tag"
	"coding.net/vco/mder/modules/watch"
	"coding.net/vco/mder/routers"
	_ "coding.net/vco/pongo2ext"
	"github.com/Unknwon/macaron"
	"github.com/macaron-contrib/pongo2"
	"net/http"
	"os"
)

const (
	HostVar    = "VCAP_APP_HOST"
	PortVar    = "VCAP_APP_PORT"
	env        = "MACARON_ENV"
	PORT       = "10086"
	static_dir = "static"
)

func init() {
	os.Setenv(env, macaron.PROD)
}

func main() {

	m := macaron.Classic()

	m.Use(macaron.Static(static_dir))
	m.Use(pongo2.Pongoer(pongo2.Options{
		Directory:  "templates",
		Extensions: []string{".tmpl", ".html"},
	}))

	//common setting
	m.Use(func(ctx *macaron.Context) {
		ctx.Data["tags"] = tag.New()
		ctx.Data["uri"] = ctx.Params("*")
		ctx.Data["mder"] = models.NewMderMap()
		ctx.Next()

	})
	chooseMode()

	m.Get("/", routers.Home)
	m.Any("/mder-webhook/update", routers.Webhook) //webhook
	m.Get("/feed/rss", routers.Rss)                //rss
	m.Get("/feed/atom", routers.Atom)              //atom
	m.Get("/about", routers.About)                 //about
	m.Get("/archive", routers.Archive)             //archive
	m.Get("/robots.txt", routers.Robots)           //robots
	m.Get("/**", routers.View)
	//webhook

	http.ListenAndServe(":"+getPort(), m)

}

func chooseMode() {
	watch.Run()
}

func getPort() string {
	if port := os.Getenv(PortVar); port == "" {
		return PORT
	} else {
		return port
	}
}
